import { User } from '@/core/user/entities/user.entity';
import { Injectable, Inject } from '@nestjs/common';
import { Redis } from 'ioredis'; // 修改导入方式

@Injectable()
export class RedisService {
  constructor(@Inject('REDIS_CLIENT') private readonly redisClient: Redis) {}

  async setUserToken(user: User, token: string): Promise<void> {
    const key = `rest:wechat:user:${user.openId}`; // 使用openId作为key的一部分

    // 同时存储token和用户数据，设置1天(86400秒)过期
    await this.redisClient.set(
      key,
      JSON.stringify({ ...user, token }), // 将用户数据和token合并存储
      'EX',
      86400,
    );
  }

  async getUserToken(openid: string): Promise<User> {
    const key = `rest:wechat:user:${openid}`;
    console.log('key', key);
    const userInfo = await this.redisClient.get(key);
    return userInfo ? (JSON.parse(userInfo) as User) : null;
  }

  async deleteUserToken(openid: string): Promise<void> {
    const key = `rest/user/wechat/${openid}`;
    await this.redisClient.del(key);
  }
}
